#! /usr/bin/env python
# -*- coding: utf-8 -*-

from qcloud_cos import CosConfig, CosS3Client
from django.conf import settings
from sts.sts import Sts
from qcloud_cos.cos_exception import CosServiceError


def create_bucket(bucket, region=settings.REGION):
    config = CosConfig(Region=region, SecretId=settings.SECRET_COS_ID, SecretKey=settings.SECRET_COS_KEY)
    client = CosS3Client(config)

    client.create_bucket(
        Bucket=bucket,
        ACL='public-read'
    )

    # 跨域
    cors_config = {
        'CORSRule': [
            {
                'MaxAgeSeconds': 500,
                'AllowedOrigin': '*',
                'AllowedMethod': ['GET', 'PUT', 'HEAD', 'POST', 'DELETE'],
                'AllowedHeader': '*',
                'ExposeHeader': '*'
            }
        ]
    }
    client.put_bucket_cors(
        Bucket=bucket,
        CORSConfiguration=cors_config,
    )


def upload_to_bucket(bucket, key, body, region=settings.REGION):
    config = CosConfig(Region=region, SecretId=settings.SECRET_COS_ID, SecretKey=settings.SECRET_COS_KEY)
    client = CosS3Client(config)

    client.upload_file_from_buffer(
        Bucket=bucket,
        Key=key,
        Body=body
    )

    url = f'https://{bucket}.cos.{region}.myqcloud.com/{key}'
    return url


def delete_file(bucket, key, region=settings.REGION):
    config = CosConfig(Region=region, SecretId=settings.SECRET_COS_ID, SecretKey=settings.SECRET_COS_KEY)
    client = CosS3Client(config)

    client.delete_object(
        Bucket=bucket,
        Key=key,
    )


def delete_file_list(bucket, key_list, region=settings.REGION):
    config = CosConfig(Region=region, SecretId=settings.SECRET_COS_ID, SecretKey=settings.SECRET_COS_KEY)
    client = CosS3Client(config)

    objects = {
        "Quiet": "true",
        "Object": key_list
    }

    client.delete_objects(
        Bucket=bucket,
        Delete=objects,
    )


def get_cos_token(bucket, region):
    config = {
        # 临时密钥有效时长，单位是秒
        'duration_seconds': 300,
        'secret_id': settings.SECRET_COS_ID,
        # 固定密钥
        'secret_key': settings.SECRET_COS_KEY,
        # 换成你的 bucket
        'bucket': bucket,
        # 换成 bucket 所在地区
        'region': region,
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allow_prefix': '*',
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            # 简单上传
            'name/cos:PutObject',
            'name/cos:PostObject',
            # 分片上传
            'name/cos:InitiateMultipartUpload',
            'name/cos:ListMultipartUploads',
            'name/cos:ListParts',
            'name/cos:UploadPart',
            'name/cos:CompleteMultipartUpload'
        ],

    }

    sts = Sts(config)
    return sts.get_credential()


def check_file(bucket, key, region=settings.REGION):
    config = CosConfig(Region=region, SecretId=settings.SECRET_COS_ID, SecretKey=settings.SECRET_COS_KEY)
    client = CosS3Client(config)

    res = client.head_object(bucket, key)
    return res


def delete_bucket(bucket, region=settings.REGION):
    """ 删除桶"""

    config = CosConfig(Region=region, SecretId=settings.SECRET_COS_ID, SecretKey=settings.SECRET_COS_KEY)
    client = CosS3Client(config)
    # 删除所有文件
    # 1. 找到同种所有文件
    while True:
        part_objs = client.list_objects(bucket)
        contents = part_objs.get('Contents')

        # 删除完毕，contents为空
        if not contents:
            break

        # 2. 批量删除
        key_list = [{"Key": item["Key"]} for item in contents]
        objects = {
            "Quiet": "true",
            "Object": key_list
        }

        client.delete_objects(
            Bucket=bucket,
            Delete=objects,
        )

        if part_objs['IsTruncated'] == 'false':
            break

    # 删除所有碎片
    try:
        while True:
            part_upload = client.list_multipart_uploads(bucket)
            uploads = part_upload.get('Upload')

            # 删除完毕，uploads为空
            if not uploads:
                break

            # 2. 批量删除
            for item in uploads:
                client.abort_multipart_upload(bucket, item['Key'], item['Upload'])

            if part_upload['IsTruncated'] == 'false':
                break

        # 删除桶
        client.delete_bucket(bucket)

    except CosServiceError as e:
        pass

